package com.kx.game.center.api.request;

import java.util.UUID;

import com.kx.game.center.api.IConfig;
import com.kx.game.center.api.IGameCenterRequest;
import com.kx.game.center.api.IGameCenterResponse;
import com.kx.game.center.utils.HttpUtil;

public abstract class AbstractRequest<T extends IGameCenterResponse> implements
		IGameCenterRequest<T> {

	private String url;

	private IConfig config;

	public AbstractRequest(String url) {
		this.url = url;
	}

	@Override
	public T send() {
		this.url = config.getDomain() + url + "&gameID=" + config.getGameID()
				+ "&serverID=" + config.getServerID();
		try {
			return doRequest(false,"");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 发送HTTP请求
	 * 
	 * @return
	 */
	protected T doRequest(boolean POST,String postContent) {
		T response = null;
		long time = 0;
		try {
			response = getResponseClass().newInstance();
			String uuid = UUID.randomUUID().toString();

			recordUrl(uuid, url);

			long beginTime = System.currentTimeMillis();

			String result = HttpUtil.getUrl(url, config.getTimeOut(), POST, postContent);

			long endTime = System.currentTimeMillis();

			time = endTime - beginTime;

			config.getRecord().recordInfo(
					uuid + "\t" + result + "\tTime:" + time + "ms");
			response.setCostTime(endTime);

			response.parseResponse(result);

		} catch (Exception e) {
			config.getRecord().recordError("#PLATFORM.LOCAL.REQUEST.ERROR:", e);
			e.printStackTrace();
		}

		return response;
	}

	protected void recordUrl(String uuid, String url) {
		config.getRecord().recordInfo(uuid + "\t" + url);
	}

	public IConfig getConfig() {
		return config;
	}

	public void setConfig(IConfig config) {
		this.config = config;
	}

}
